import logging
import os
from logging.handlers import RotatingFileHandler
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# Log配置
log_dir = "logs"
log_file = os.path.join(log_dir, "app.log")
error_log_file = os.path.join(log_dir, "error.log")
access_log_file = os.path.join(log_dir, "access.log")

# 确保日志目录存在
os.makedirs(log_dir, exist_ok=True)

# 创建全局 logger
logger = logging.getLogger("my_app")
logger.setLevel(logging.DEBUG)

# 避免重复添加 handler
if not logger.handlers:
    # 详细日志格式
    detailed_formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(funcName)s - %(message)s"
    )
    
    # 简单日志格式
    simple_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")

    # 主日志文件 handler（自动轮转，最多保留5个日志文件，每个最大10MB）
    file_handler = RotatingFileHandler(log_file, maxBytes=1024*1024*10, backupCount=5)
    file_handler.setFormatter(detailed_formatter)
    file_handler.setLevel(logging.DEBUG)

    # 错误日志文件 handler
    error_handler = RotatingFileHandler(error_log_file, maxBytes=1024*1024*10, backupCount=5)
    error_handler.setFormatter(detailed_formatter)
    error_handler.setLevel(logging.ERROR)

    # 访问日志文件 handler
    access_handler = RotatingFileHandler(access_log_file, maxBytes=1024*1024*10, backupCount=5)
    access_handler.setFormatter(simple_formatter)
    access_handler.setLevel(logging.INFO)

    # 控制台 handler
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(simple_formatter)
    console_handler.setLevel(logging.INFO)

    # 添加 handler
    logger.addHandler(file_handler)
    logger.addHandler(error_handler)
    logger.addHandler(access_handler)
    logger.addHandler(console_handler)

# 创建专门的访问日志记录器
access_logger = logging.getLogger("access")
access_logger.setLevel(logging.INFO)
if not access_logger.handlers:
    access_handler = RotatingFileHandler(access_log_file, maxBytes=1024*1024*10, backupCount=5)
    access_handler.setFormatter(simple_formatter)
    access_logger.addHandler(access_handler)
    access_logger.propagate = False

# 创建专门的错误日志记录器
error_logger = logging.getLogger("error")
error_logger.setLevel(logging.ERROR)
if not error_logger.handlers:
    error_handler = RotatingFileHandler(error_log_file, maxBytes=1024*1024*10, backupCount=5)
    error_handler.setFormatter(detailed_formatter)
    error_logger.addHandler(error_handler)
    error_logger.propagate = False

# Prometheus配置
PROMETHEUS_URL = os.getenv("PROMETHEUS_URL", "")


# 企业微信配置
WECHAT_CORP_ID = os.getenv("WECHAT_CORP_ID", "")
WECHAT_CORP_SECRET = os.getenv("WECHAT_CORP_SECRET", "")
WECHAT_AGENT_ID = os.getenv("WECHAT_AGENT_ID", "")
WECHAT_WEBHOOK = os.getenv("WECHAT_WEBHOOK", "")
WECHAT_ROBOT_WEBHOOK = os.getenv("WECHAT_ROBOT_WEBHOOK", "")
BOT_NAME = os.getenv("BOT_NAME", "Prometheus监控机器人")
WECHAT_TOKEN = os.getenv("WECHAT_TOKEN", "")
WECHAT_ENCODING_AES_KEY = os.getenv("WECHAT_ENCODING_AES_KEY", "")

# flask配置
SERVER_HOST = os.getenv("SERVER_HOST", "0.0.0.0")
SERVER_PORT = int(os.getenv("SERVER_PORT", "5000"))

# 企业微信API配置
WECHAT_API_BASE = "https://qyapi.weixin.qq.com"
WECHAT_ACCESS_TOKEN_URL = f"{WECHAT_API_BASE}/cgi-bin/gettoken"
WECHAT_SEND_MESSAGE_URL = f"{WECHAT_API_BASE}/cgi-bin/message/send"

# 消息长度限制配置
WECHAT_MAX_MESSAGE_LENGTH = 2048  # 企业微信文本消息最大长度
WECHAT_MAX_MARKDOWN_LENGTH = 4096  # 企业微信Markdown消息最大长度

# promql
PROMQL_TEMPLATES = {
    "node_status": 'kube_node_status_condition{{project_name="{project_name}", job="kube-state-metrics", condition="Ready", status="true"}}',
    "memory_usage": '100 - node_memory_MemAvailable_bytes{{project_name="{project_name}"}} / node_memory_MemTotal_bytes{{project_name="{project_name}"}} * 100',
    "cpu_usage": '100 - (avg by (instance) (rate(node_cpu_seconds_total{{project_name="{project_name}", mode="idle"}}[5m])) * 100)',
    "cpu_load": 'node_load1{{project_name="{project_name}"}}',
    "disk_usage": 'topk(1, 100 - (node_filesystem_avail_bytes{{project_name="{project_name}", mountpoint!~".+/docker.+|.+/containers.+|.+/kubelet.+", fstype=~"ext.*|xfs"}} * 100) / node_filesystem_size_bytes{{project_name="{project_name}", mountpoint!~".+/docker.+|.+/containers.+|.+/kubelet.+", fstype=~"ext.*|xfs"}}) by (instance)',
    "pod_status": 'kube_pod_status_phase{{project_name="{project_name}", job="kube-state-metrics", phase !~ "Running"}} != 0',
    "redis_status": 'redis_up{{project_name="{project_name}"}}',
    "zookeeper_status": 'zk_up{{project_name="{project_name}"}}',
    "mysql_status": 'mysql_up{{project_name="{project_name}"}}',
    "mysql_connections": 'mysql_global_status_threads_connected{{project_name="{project_name}"}}',
    "mysql_slow_queries": 'increase(mysql_global_status_slow_queries{{project_name="{project_name}"}}[5m])'
}

# promql对应关系
PARAM_TO_PROMQL = {
    "节点状态": "node_status",
    "内存使用率": "memory_usage",
    "CPU利用率": "cpu_usage",
    "CPU负载": "cpu_load",
    "磁盘使用率": "disk_usage",
    "Pod状态": "pod_status",
    "Redis状态": "redis_status",
    "Zookeeper状态": "zookeeper_status",
    "MySQL状态": "mysql_status",
    "MySQL连接数": "mysql_connections",
    "MySQL慢查询": "mysql_slow_queries"
}